github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/generators/backend_vanillajs_rest.go.tpl (about)

     1  package backend
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"net"
     8  	"net/http"
     9  	"net/url"
    10  	"os"
    11  	"strings"
    12  	"time"
    13  
    14  	"github.com/pojntfx/hydrapp/hydrapp/pkg/utils"
    15  )
    16  
    17  func StartServer(ctx context.Context, addr string, localhostize bool) (string, func() error, error) {
    18  	if strings.TrimSpace(addr) == "" {
    19  		addr = ":0"
    20  	}
    21  
    22  	listener, err := net.Listen("tcp", addr)
    23  	if err != nil {
    24  		return "", nil, err
    25  	}
    26  
    27  	mux := http.NewServeMux()
    28  
    29  	mux.HandleFunc("/servertime", func(w http.ResponseWriter, r *http.Request) {
    30  		if _, err := w.Write([]byte("Go server time: " + time.Now().Format(time.RFC3339))); err != nil {
    31  			panic(err)
    32  		}
    33  	})
    34  
    35  	mux.HandleFunc("/ifconfigio", func(w http.ResponseWriter, r *http.Request) {
    36  		res, err := http.Get("https://ifconfig.io/all.json")
    37  		if err != nil {
    38  			if _, err := w.Write([]byte(err.Error())); err != nil {
    39  				panic(err)
    40  			}
    41  
    42  			return
    43  		}
    44  		defer res.Body.Close()
    45  
    46  		data, err := ioutil.ReadAll(res.Body)
    47  		if err != nil {
    48  			if _, err := w.Write([]byte(err.Error())); err != nil {
    49  				panic(err)
    50  			}
    51  
    52  			return
    53  		}
    54  
    55  		if _, err := w.Write(data); err != nil {
    56  			panic(err)
    57  		}
    58  	})
    59  
    60  	mux.HandleFunc("/envs", func(w http.ResponseWriter, r *http.Request) {
    61  		b, err := json.Marshal(os.Environ())
    62  		if err != nil {
    63  			panic(err)
    64  		}
    65  
    66  		if _, err := w.Write(b); err != nil {
    67  			panic(err)
    68  		}
    69  	})
    70  
    71  	go func() {
    72  		if err := http.Serve(listener, mux); err != nil {
    73  			if strings.HasSuffix(err.Error(), "use of closed network connection") {
    74  				return
    75  			}
    76  
    77  			panic(err)
    78  		}
    79  	}()
    80  
    81  	url, err := url.Parse("http://" + listener.Addr().String())
    82  	if err != nil {
    83  		return "", nil, err
    84  	}
    85  
    86  	if localhostize {
    87  		return utils.Localhostize(url.String()), listener.Close, nil
    88  	}
    89  
    90  	return url.String(), listener.Close, nil
    91  }