github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/app_listenAndServe.go (about)

     1  // Copyright 2017-present Kirill Danshin and Gramework contributors
     2  // Copyright 2019-present Highload LTD (UK CN: 11893420)
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  
    11  package gramework
    12  
    13  import (
    14  	"errors"
    15  	"flag"
    16  	"os"
    17  	"strings"
    18  )
    19  
    20  // ListenAndServe HTTP on given addr.
    21  // runs flag.Parse() if !flag.Parsed() to support
    22  // --bind flag.
    23  func (app *App) ListenAndServe(addr ...string) error {
    24  	checks()
    25  	var bind string
    26  	if len(addr) > 0 {
    27  		bind = addr[0]
    28  	} else {
    29  		bind = os.Getenv("PORT")
    30  		if len(bind) > 0 && !strings.Contains(bind, ":") {
    31  			bind = ":" + bind
    32  		}
    33  		if bind == "" && !app.flagsRegistered {
    34  			app.RegFlags()
    35  		}
    36  	}
    37  
    38  	if !flag.Parsed() && !flagsDisabled {
    39  		flag.Parse()
    40  	}
    41  
    42  	if app.Flags.values != nil {
    43  		if bindFlag, ok := app.Flags.values["bind"]; ok {
    44  			bind = *bindFlag.Value
    45  		}
    46  	}
    47  
    48  	if bind == "" {
    49  		return errors.New("no bind address provided")
    50  	}
    51  
    52  	l := app.internalLog.WithField("bind", bind)
    53  	l.Info("Starting HTTP")
    54  
    55  	var err error
    56  	srv := app.copyServer()
    57  	app.runningServersMu.Lock()
    58  	app.runningServers = append(app.runningServers, runningServerInfo{
    59  		bind: bind,
    60  		srv:  srv,
    61  	})
    62  	app.runningServersMu.Unlock()
    63  	if err = srv.ListenAndServe(bind); err != nil {
    64  		l.Errorf("ListenAndServe failed: %s", err)
    65  	}
    66  
    67  	return err
    68  }