Looking at the ngrams of both, good night has a more frequent use. Goodnight has only appeared recently, suggesting that it has been introduced – but is correct to use. I would write "Goodnight, sweetheart" and "Have a good night". I also think that "goodnight" is just a shortened way of saying "have a good night". More @Wikipedia
Hover over any link to get a description of the article. Please note that search keywords are sometimes hidden within the full article and don't appear in the description or title.