Embed Caddy on golang

I got a golang web application which has frontend and backend separation via apis. I was serving static files in the same port using http.FileServer(http.Dir(ServerHome+"/webapps/apieditor/"), it was with very limited features.

Now I’m trying to use Caddy to server the static content on a different port without altering the apis port. I tired to follow the documentation on embedding Caddy in golang but couldn’t find a concert example.

So I ended up using the Caddy binary externally. Does anyone have a good example of embedding Caddy server in go?.

I’d say Caddy’s main() function (which we actually call Run() which is called from main()) is a pretty good example:

https://github.com/mholt/caddy/blob/7157bdc79d38e203386d7e12d7065d884166c431/caddy/caddymain/run.go#L101-L114

As you can see it’s really quite easy. :slight_smile: Hope that helps!

So, I was just doing this right now, but I got this:

panic: no server types plugged in

goroutine 1 [running]:
panic(0x4e8cc0, 0xc42000c790)
	/usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
	/home/bruno/other-projects/caddy-messaround/main.go:16 +0xe0

Any idea on what might be going on? What am I missing?

Edit: Caddyfile

localhost:8090

Code:

package main

import "github.com/mholt/caddy"

func main() {
	caddy.AppName = "foo"
	caddy.AppVersion = "1.0.0"

	caddyfile, err := caddy.LoadCaddyfile("http")
	if err != nil {
		panic(err)
	}

	instance, err := caddy.Start(caddyfile)
	if err != nil {
		panic(err)
	}

	instance.Wait()
}

Oh yeah – you have to import a server type, too. Otherwise Caddy doesn’t know how to serve anything. (I do need to improve the docs here… been working on a new site and updated developer wiki though!)

import "github.com/mholt/caddy/caddyhttp"

That should do it.

1 Like

Yup, that did the trick. Awesome! Thanks, Matt :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.