使用程式內建caddy server

package webserver

import (
	"io/ioutil"
	"log"
	"os"

	"github.com/mholt/caddy"
	_ "github.com/mholt/caddy/caddyhttp"
)

func init() {
	caddy.SetDefaultCaddyfileLoader("default", caddy.LoaderFunc(defaultLoader))
}

func defaultLoader(serverType string) (caddy.Input, error) {
	contents, err := ioutil.ReadFile(caddy.DefaultConfigFile)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}
	log.Printf("Loading Caddyfile: %s\n", string(contents))
	log.Println(serverType)
	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       caddy.DefaultConfigFile,
		ServerTypeName: serverType,
	}, nil
}

func GetServer() *caddy.Instance {
	caddy.AppName = "test"
	caddy.AppVersion = "0.1"

	caddyfile, err := caddy.LoadCaddyfile("http")
	if err != nil {
		log.Fatalf("Unable to load caddyfile: %s", err)
	}

	inst, err := caddy.Start(caddyfile)
	if err != nil {
		log.Fatalf("Unable to start caddy server: %s", err)
	}
	return inst
}

caddyfile

:80
proxy / localhost:8000
log stdout

simpleserver.go

package simpleserver

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

// Ping is a GET API that responds with a simple text
func Ping(rw http.ResponseWriter, r *http.Request) {
	fmt.Fprint(rw, "Pong")
}

// StartHTTPServer starts the server in port 8000 using mux router
func StartHTTPServer() {
	r := mux.NewRouter()
	r.HandleFunc("/ping", Ping)
	address := "0.0.0.0:8000"
	log.Printf("Starting http server on %s\n", address)
	http.ListenAndServe(address, r)
}

合併執行 main.go

package main

import (
	"./backendarmy-blog/embed_caddy/simpleserver"
	"./embed_caddy/webserver"
)

func main() {
	caddyInst := webserver.GetServer()
	simpleserver.StartHTTPServer()
	caddyInst.Wait()
}

參考資料