Live reload for Go web development

Overview

livedev

livedev is a development proxy server for golang that allows live reloading.
It supports multiple server configuration.
It uses the request's header "Host" field to determine which server the request should be routed to.
If no match is found the request is routed the default server.

Compatible with: go version go1.0.2+

Features

  • Cross-platform
  • Unobstructive. No code change required
  • Simple json configuration file
  • Multiple server support
  • Automated build service.
  • Dependency change detection
  • Autorealod the page when assets (js, css, image, html...) change

Installation

go get -u github.com/qrtz/livedev

Configuration

livedev is controlled by a json configuration file:

  • port: (int, default:"80") proxy port
  • GOROOT: (string, optional)
  • GOPATH: (string, optional)
  • server: ([]Server) A list of Server object with the following options:
    • GOROOT: (string, optional) Server specific GOROOT for compiling with different go version
    • GOPATH: ([]string, optional) Server specific GOPATH.
    • host: (string) server hostname (must be unique)
    • port: (int, optional) server port
    • target: (string, optional) Build target. The file that contains the main function.
      if target is not in the GOPATH, livedev will attempt to add it by guessing the workspace from the filename.
      When target is ommited, the build step is skipped.
    • workingDir: (string, optional) workingDir specifies the working directory of the server executable. If workingDir is empty, it defaults to the parent directory of the executable.
    • env: (map, optional) A map of key value pairs to set as environment variables on the server.
    • resources: (optional) A list of resources such as template files. Any change to these files will cause the server to restart.
      • ignore: (string, optional) filename pattern to ignore.
      • paths: ([]string) A list of files or directories to monitor
    • assets: (optional) A list of assets such as css, javascript, image files. Any change to these files will cause a page to reload.
      • ignore: (string, optional) filename pattern to ignore.
      • paths: ([]string) A list of files or directories to monitor
    • bin: (string, optional) server executable file. When absent, it default to /tmp/livedev[hostname]
    • builder: ([]string, optional) To use a builder other than the go build tool. The first element is the command and the rest its arguments
    • startup: ([]string, optional) server startup argument list
    • default: (bool, optinal) Specifies the default server.
      Defaults to the first server in the list
    • startupTimeout: (int, default=5) Specifies the time (in seconds) limit to wait for the server to complete the startup operation.

In the server configuration block, properties can be referred on using "${PROPERTY}" or "$PROPERTY" variable substutitions
Along with the configuration properties, the process environment variables are also available.

Usage

$ livedev -c config.json

config.json

{
    "port":8080,
    "server":[
        {
            "host":"dev.service1.com",
            "port": 8081,
            "target":"/projects/src/serviceone/main.go",
            "workingDir": "/projects/src/serviceone"
            "resources":{
                "ignore":"static*",
                "paths":["${workingDir}/templates"]
             },
            "startup": ["-host", "$host", "-port", "${port}"]
            "bin":"/projects/bin/serviceone"
        },
        {
            "host":"dev.service2.com",
            "env": {
                "HOST": "${host}",
                "PORT": "${port}"
            },
            "target":"/projects/src/servicetwo/main.go",
            "workingDir": "/projects/src/servicetwo"
            "resources":{
                "ignore":"static*",
                "paths":["${workingDir}/templates"]
             },
            "bin":"/projects/bin/servicetwo"
        }
    ]
}
# host file
127.0.0.1 dev.service1.com dev.service2.com

dev.service1.com

URL: http://dev.service1.com:8080
The request is forwarded to http://dev.serviceone.com:8081
The server access "host and "port" from the command-line argument as specified in the "startup" property of the configuration

packgage main

import (
    "flag"
    "net"
    "net/http"
) 

func main(){
    host := flag.String("host", "localhost", "host name")
    port := flag.String("port", "8081", "port")

    flag.Parse()

    addr := net.JoinHostPort(*host, *port)
    http.ListenAndServe(addr, handler)
}

dev.service2.com

URL: http://dev.service2.com:8080
The request is forwarded to http://dev.service2.com:`port`. Where port is a randomly generated port.
The server gets access to "host and "port" from environment variables as specified in the "env" property of the configuration

packgage main

import (
    "net"
    "net/http"
    "os"
) 

func main(){
    host := os.Getenv("HOST")
    port := os.Getenv("PORT")
    addr := net.JoinHostPort(host, port)
    http.ListenAndServe(addr, handler)
}

Live Reload

Livedv uses a deceptively simple protocol to enable live reload.
It injects a small inline javascript into HTML pages at the end of the document right before the closing body tag.
The script opens a websocket connection and reloads the page once the connection is closed.
Live reload events are as follow.

  • Change to go files:
    Rebuild, Restart the server and close liveReload websocket connections
  • Change to files listed under "resources" in the configuration:
    Restart the server and close liveReload websocket connections
  • Change to files listed under "assets" in the configuration:
    Close liveReload websocket connections

Closing liveReload connections causes all connected HTML pages to reload.

Comments
  • Config file help please?

    Config file help please?

    I would like to try livedev, but I am having issues getting it to compile my project.It runs and parses the livedev.json file but when I refresh the web page, I get this error:

    BUILD ERROR: GetFileAttributesEx controllers.go: The system cannot find the file specified.
    

    Here is my livedev.json file contents (I've tried without the GOROOT and GOPATH server params and also a relative path for the target parameter without succes:

    {
        "port":9001,
        "server":[
            {
                "GOROOT":"C:/Go",
                "GOPATH":["C:/Users/Nuri/Dropbox (Personal)/go"],
                "host":"localhost",
                "port": 9000,
                "target":"C:/Users/Nuri/Dropbox (Personal)/go/src/github.com/nkev/web/app/main.go",
                "bin":"/src/github.com/nkev/web/app/web.exe",
                "default":true
            }
        ]
    }
    

    Here is my directory structure:

    image

    The command I use from the root "web" folder is:

    livedev -c livedev.json
    

    When it runs, I get:

    Livedev 0.1.8
    Host: localhost:9000
    Proxy:localhost:9001
    

    But when I refresh my browser (Chrome on Windows 8.1) I get the error:

    BUILD ERROR: GetFileAttributesEx controllers.go: The system cannot find the file specified.
    

    Can you see what I'm doing wrong?

    opened by nkev 8
  • Unclear workflow

    Unclear workflow

    Hey there,

    I'm not entirely sure how to use this utility. I have two servers defined in my config.json file. The hostnames for both exist in my hosts file and are mapped to 127.0.0.1. The ports that both go apps listen on are also mapped correctly. I don't want this utility listening on Port 80, but it uses the hostname header to proxy the requests. How am I supposed to call my services then?

    {
        "port": 9000,
        "server":[
            {
                "host": "local.service1.com",
                "port": 5000,
                "target": "/Users/foo/go/src/bitbucket.org/service1/server.go",
                "startupTimeout": 5
            },
            {
                "host": "local.service2.com",
                "port": 5001,
                "target": "/Users/foo/go/src/bitbucket.org/service2/server.go",
                "startupTimeout": 5
            }
        ]
    }
    
    opened by seanlindo 2
  • added port to live reload html

    added port to live reload html

    In my setup i use browsersync to reload static resources and i would like to use livedev to reload go sources and resources. The setup looks like below:

    browsersync (port 3000) -> livedev (port 7070) -> go app (port 8080)

    The problem with this setup is that livedev creates a redirect loop, because it uses current port of the browser for the websocket connection. This fails because the current port is the one from browsersync.

    This change will add the port to the live reload html snippet.

    opened by sdorra 1
  • Have you considered using goproxy?

    Have you considered using goproxy?

    GoProxy will have you automatically support https, will not send proxy headers, and will probably save some code.

    I'll be more than happy to help integrating it/send pull request.

    https://github.com/elazarl/goproxy

    opened by elazarl 1
  • Add configurable watcher delay

    Add configurable watcher delay

    Thanks for this tool, it's very helpful.

    But I faced the problem. In our project we use pug templates which compile to html. When I change some template, multiple html files start to rebuild. livedev starts the server restart when it get the first file change notification, but html files are still rebuilding and triggering new fs notifications. It causes multiple server restarts one after the other and takes a lot of time. So it would be great to have a chance to set some delay between fs event and server restart.

    opened by mkhazov 2
Owner
null
ide-gen is a tool for development workspace prepare automation by automatic VCS repositories discovery and clone and project generation for supported IDEs.

ide-gen is a tool for development workspace prepare automation by automatic VCS repositories discovery and clone and project generation for supported IDEs.

null 8 May 8, 2022
Web based, Go IDE.

Strukture IDE Beta II Go lang IDE. Built with GopherSauce About project IDE runs as a server and is accessed via web browser. Being a web server, the

The Strukture IDE 355 Nov 28, 2022
Live reload utility for Go web servers

gin gin is a simple command line utility for live-reloading Go web applications. Just run gin in your app directory and your web app will be served wi

Jeremy Saenz 4k Jan 4, 2023
☁️ Live reload for Go apps

Air ☁️ Live reload for Go apps Motivation When I get started with developing websites in Go and gin framework, it's a pity that gin lacks live-reloadi

Rick Yu 8.9k Jan 1, 2023
Ambiente com Docker de "live-reload" para aplicações Go

Ambiente Go Um ambiente de "live reload", onde as alterações no código são observadas e re-executadas automaticamente, com Docker e Docker Compose. O

Davi Marcondes Moreira 3 Jun 17, 2022
🔎 gowatch Live reload for go apps.

Watch ?? gowatch Live reload for go apps Motivation I had no app to live reload my Go programs. Usage Install go install github.com/gelfand/gowatch ◆

Eugene 0 Dec 29, 2021
A local server with real-time reload function designed for static website preview or development

中文 | English ?? 介绍 reserver 是一款为静态网站预览或开发设计的具有实时重新加载功能的本地服务器。 其主要运用场景为: 单页应用的预览(例如Vue编译之后的项目不可以直接通过file://协议进行访问) 具有ajax请求的页面(因浏览器安全限制,默认禁止file://协议进行

憧憬Licoy 7 Aug 23, 2022
Reload a specified go program automatically by monitoring a directory.

gowatcher A bash script to automatically reload a go program when .go or .html files change in the monitored directory. It uses inotify. Installation

Nick Janetakis 16 Jul 7, 2020
Reload Go code in a running process at function/method level granularity

got reload? Function/method-level stateful hot reloading for Go! Status Very much work in progress.

null 34 Nov 9, 2022
Sidecar to watch a config folder and reload a process when it changes

A small (3MB uncompressed docker image), efficient (via inotify) sidecar to trigger application reloads when configuration changes.

Florent Delannoy 25 Dec 29, 2022
GCP Cloud Functions ready to Go starter with hot reload 🔥

GCP Cloud Functions - Go Starter Features: funcFramework already set up - ready for local development and testing. Hot Reload ready-to-go thanks to th

Eric Crescioni 0 Dec 16, 2021
Golang http&grpc server for gracefully shutdown like nginx -s reload

supervisor Golang http & grpc server for gracefully shutdown like nginx -s reload if you want a server which would be restarted without stopping servi

Terry Fei 0 Jan 8, 2022
This is a hot reload tooling for go

hotpocket This is a hot reload tooling for go Usage First need to have a json file in the root of your project. Name it as a hotpocket.json. It Should

Rasulov Emirlan 4 Jul 17, 2022
Instant, disposable, single-binary web based live chat server. Go + VueJS.

Niltalk Niltalk is a web based disposable chat server. It allows users to create password protected disposable, ephemeral chatrooms and invite peers t

Kailash Nadh 858 Jan 4, 2023
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch

It is still under development, so please do not use it. We plan to release v.1.0.0 in the summer. roche is a web framework optimized for microservice

Riita 14 Sep 19, 2022
Go-web-dev - Web Development With Google's Golang Programming Language Code Snippet and Exercises.

Web Development With Google's Golang Programming Language Code Snippet and Exercises This repository contains my code snippets, hands on exercises and

null 2 Jan 16, 2022
Suppress commit to master and development, merge branch to master and development

git-extension masterと名前のつくブランチをマージするのは禁止 masterとdevelopmentブランチに直接commitやmergeするのは禁止 masterブランチを親に新規ブランチを作成するのは禁止 どうしてもmasterやdevelopmentブランチに操作をしたい時は

y-oga 1 Nov 8, 2021
Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading.

#1 Golang live reload and task runner Content - ⭐️ Top Features - ???? Get started - ?? Config sample - ?? Commands List - ?? Support and Suggestions

Oxequa 4.3k Jan 6, 2023
Server-sent live updates: protocol and reference implementation

Protocol and Reference Implementation Mercure is a protocol allowing to push data updates to web browsers and other HTTP clients in a convenient, fast

Kévin Dunglas 3.2k Jan 1, 2023