The easiest way to create web applications with Go

Build Status

web.go

web.go is the simplest way to write web applications in the Go programming language. It's ideal for writing simple, performant backend web services.

Overview

web.go should be familiar to people who've developed websites with higher-level web frameworks like sinatra or web.py. It is designed to be a lightweight web framework that doesn't impose any scaffolding on the user. Some features include:

  • Routing to url handlers based on regular expressions
  • Secure cookies
  • Support for fastcgi and scgi
  • Web applications are compiled to native code. This means very fast execution and page render speed
  • Efficiently serving static files

Installation

Make sure you have the a working Go environment. See the install instructions. web.go targets the Go release branch.

To install web.go, simply run:

go get github.com/hoisie/web

To compile it from source:

git clone git://github.com/hoisie/web.git
cd web && go build

Example

package main
    
import (
    "github.com/hoisie/web"
)
    
func hello(val string) string { return "hello " + val } 
    
func main() {
    web.Get("/(.*)", hello)
    web.Run("0.0.0.0:9999")
}

To run the application, put the code in a file called hello.go and run:

go run hello.go

You can point your browser to http://localhost:9999/world .

Getting parameters

Route handlers may contain a pointer to web.Context as their first parameter. This variable serves many purposes -- it contains information about the request, and it provides methods to control the http connection. For instance, to iterate over the web parameters, either from the URL of a GET request, or the form data of a POST request, you can access ctx.Params, which is a map[string]string:

package main

import (
    "github.com/hoisie/web"
)
    
func hello(ctx *web.Context, val string) { 
    for k,v := range ctx.Params {
		println(k, v)
	}
}   
    
func main() {
    web.Get("/(.*)", hello)
    web.Run("0.0.0.0:9999")
}

In this example, if you visit http://localhost:9999/?a=1&b=2, you'll see the following printed out in the terminal:

a 1
b 2

Documentation

API docs are hosted at https://hoisie.github.io/web/

If you use web.go, I'd greatly appreciate a quick message about what you're building with it. This will help me get a sense of usage patterns, and helps me focus development efforts on features that people will actually use.

About

web.go was written by Michael Hoisie

Owner
Michael Hoisie
Working on Android testing tools at Google.
Michael Hoisie
Comments
  • Various

    Various

    Hi,

    • Removed examples that called functions that just aren't there
    • Fixed the rest of the examples
    • Removed Makefiles
    • Ran "go fmt" on everything

    Best regards, Alexander Rødseth

  • Add ServeHTTP to serve as handler function (Google AppEngine Support)

    Add ServeHTTP to serve as handler function (Google AppEngine Support)

    This change support Google App Engine. #72

    If you merge this change, minimal instruction to setup google appengine with web.go is follow: #1. Setup web.go for google appengine

    $ git clone https://github.com/hoisie/web github.com/hoisie/web
    $ rm -rf github.com/hoisie/web/.git
    $ rm -rf github.com/hoisie/web/Readme.md
    $ rm -rf github.com/hoisie/web/LICENSE
    $ rm -rf github.com/hoisie/web/Makefile
    $ rm -rf github.com/hoisie/web/examples
    $ rm  -f github.com/hoisie/web/web_test.go
    

    #2. Write you app

    package mattnwebgo
    
    import (
        "github.com/hoisie/web"
        "net/http"
    )
    
    func init() {
        web.Get("/", func() string {
            return "hello"
        })
    
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            web.ServeHTTP(w, r)
        })
    }
    

    #3. Add app.yaml

    application: your-web-app
    version: 1
    runtime: go
    api_version: go1
    
    handlers:
    - url: /static
      static_dir: static
    - url: /.*
      script: _go_app
    

    #4. Upload

    $ appcfg.py update .
    

    FAQ

    If you want to use application context of appengine

    package example
    
    import (
        "appengine"
        "appengine/urlfetch"
        "github.com/hoisie/web.go"
        "http"
        "io/ioutil"
    )
    
    func init() {
        var c appengine.Context
    
        web.Get("/", func(ctx *web.Context) {
            client := urlfetch.Client(c)
    
            r, _, err := client.Get("http://www.getwebgo.com/")
            if err != nil {
                ctx.Abort(500, err.String())
                return
            }
            defer r.Body.Close()
            b, err := ioutil.ReadAll(r.Body)
            if err != nil {
                ctx.Abort(500, err.String())
                return
            }
            ctx.Write(b)
        })
    
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            c = appengine.NewContext(r)
            web.ServeHTTP(w, r)
        })
    }
    
  • Can't run Tutorial

    Can't run Tutorial

    Starting with the tutorial, I get the following error when trying to go build hello.go

    hello.go:4:5: import "github.com/hoisie/web": cannot find package

  • Go 1 Compatibility

    Go 1 Compatibility

    The following changes were made for Go 1 compatibility.

    1. Run go fix to automatically fix some of the code (os.Error -> error, for example)

    2. Manually made some changes to timestamps. Use of int64 replaced by either Time or Duration. Some constants would probably be moved to the top.

    3. Removed the Heap debug profiler since it doesn't appear to be present in that package anymore. I think the correct behavior is to use Index?

    4. Cleaned up the makefile to be only reliant on the go tool.

    While you might not take in these changes verbatim, I hope this helps! Not sure how to test locally since it tries to build the examples by installing from your master.

  • Is it possible to call methods from an interface?

    Is it possible to call methods from an interface?

    Here's a small example. This doesn't compile because web.Get doesn't like me passing an interface method.

    https://gist.github.com/Altonymous/c95c233b21ac7de3b7bc

    I've also tried... var webContext *web.Context = new(web.Context) web.Get("/machines/?", s.index(webContext))

    I'm not sure if there is a way to do this, but if there is I'd appreciate knowing how.

  • Fixed routing for request-paths which contain an encoded slash (%2F)

    Fixed routing for request-paths which contain an encoded slash (%2F)

    Assuming you have set up a route like this: web.Get("/album/(.?)/(.?)/info", AlbumInfo)

    Requests which contain an encoded slash (%2F) would now break this route, because the route handling is operating on the already url-decoded path. Consider this example:

    http://.../album/Manowar+%2F+Friends/Into+Glory+Ride+%2F+Hail+to+England/info

    The routing-handler would see this as: http://.../album/Manowar+/+Friends/Into+Glory+Ride+/+Hail+to+England/info

    My fix uses the encoded requestURI to detect the right route and then unescapes the specified arguments only before calling the user-handler.

  • arcchallenge.go example

    arcchallenge.go example

    Still having issues compiling this example with golang 1.0.2

    time do not have Nanoseconds() func strconv do not have Itoa64 method FormatInt has been suggested (likely easy to fix this one) ctx.Request do not have Params map (reports to be of type *http.Request)

  • Websocket support proposal

    Websocket support proposal

    To support this (https://github.com/hoisie/web/issues/105)

    func upgradeWebsocketHandler(wsHandler websocket.Handler) interface{} {
            return func(ctx *web.Context) {
                    wsHandler.ServeHTTP(ctx.ResponseWriter, ctx.Request);
            }
    }
    

    Removed the interface type web.ResponseWriter and replaced with http.ResponseWriter

  • Log Request in a separated method

    Log Request in a separated method

    Log more informations in console:

    • all requests (including static files)
    • duration
    • request ip

    If you are ok with this improvement, I'd like to make another PR so that the LogRequest becomes a Config option so that anyone can override the default logging behaviour.

    I'd line to also add information about:

    • whether this was a file or a handler
    • the HTTP status in the response
  • XML POST input incorrectly parsed

    XML POST input incorrectly parsed

    Sending XML thought POST seems to result in an invalid Params map.

    Test by sending some xml with xml header:

    .....

    curl -d @data/simple-request.xml -H "Content-Type: text/plain;charset=UTF-8 " http://localhost:9999/

    func hello(ctx *web.Context, val string) {
        for k,v := range ctx.Params {
            fmt.Print(k)
            fmt.Print(" -> ")
            fmt.Println(v)
        }
        ctx.WriteString("hello")
    }
    func main() {
        web.Post("/(.*)", hello)
        web.Run("0.0.0.0:9999")
    }
    
  • Enhancement: dynamic recompilation manager ... ?

    Enhancement: dynamic recompilation manager ... ?

    This is (almost) my first experience with web development using a compiled language. I've become extremely used to being able to just change my code, and when I refresh the page, it runs differently. I do this literally more than once a minute.

    Compiling a binary every time I want to see a change, even if compilation is almost instantaneous, is hard work. I don't think it's a fundamental issue with compiled languages, though -- how about if some scheme like the following was followed:

    The system is aware of the source from which it is compiled, and tracks those files for changes. When a new HTTP request comes in, if changes to the source have been made, it dies, recompiles, starts again, and then handles the request. There'd be issues if you're storing application state in memory, but ... I don't.

    I should say, this management would be done by another binary rather than the app itself. Let's call it runwebgo, and I can call it as with any other binary. And let's say for my application, called blog, I provide a plaintext file called .runwebgo, which contains:

    • a list of relative paths to sourcecode files to watch
    • a command to execute when recompilation is required (e.g. make)
    • a port on which my running app will listen

    Now, instead of running make and then ./blog every time, I just run runwebgo in the top level of my app directory. runwebgo then:

    • parses my .runwebgo file for the list of files, the command, and the port
    • watches all files for updates, setting a changed flag when a file changes
    • starts up my app
    • runs as a web server (in exactly the same way as a normal web.go app) listening on some odd port (other than the 9999 or 80 which I may have my app configured to)
    • every time a request is received, it checks the changed flag. If things have changed, it kills my app, recompiles it, re-runs it. In either case, it then sends on the request to the port of my app.
    • when it is killed, it kills my app as well.

    It could also observe changes to the .runwebgo file itself, and dynamically update the source list if I resave it.

    I imagine creating this would not be too hard or use anything outside the standard library. The upshot IMO is massive: I just run one command and leave it for my whole coding session.

  • Support context

    Support context

    Since the context package is part of standard library, I think we should support it.

    And web.go had a struct called Context and is used to passing values to handler, I think we can reuse it as a context.Context interface. The easist way to do it is embed the context.Context from http.Request.Context() to web.go's Context.

  • Fix format error in lated go version

    Fix format error in lated go version

    Fix the format error and let latest go compile can compile it.

    Bumped the go version in .travis file also, dropped old version go support, because some dependency package is not supported and can't compiled on this versions.

  • 
Fix function comments based on best practices from Effective Go

    Fix function comments based on best practices from Effective Go

    Every exported function in a program should have a doc comment. The first sentence should be a summary that starts with the name being declared. From effective go.

    PR generated by CodeLingo. Install here to drive Continuous Higher Standards.

Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

Nov 14, 2022
Provide open, community driven reusable components for building distributed applications

Components Contrib The purpose of Components Contrib is to provide open, community driven reusable components for building distributed applications. T

Nov 28, 2021
:bullettrain_side: High-performance web server for Go.
:bullettrain_side: High-performance web server for Go.

Aero is a high-performance web server with a clean API. Installation go get -u github.com/aerogo/aero/... Usage Run this in an empty directory: aero -

Dec 8, 2022
An ideally refined web framework for Go.

Air An ideally refined web framework for Go. High-performance? Fastest? Almost all web frameworks are using these words to tell people that they are t

Dec 15, 2022
Web framework for creating apps using Go in Google AppEngine

Welcome to app.go v3.0 app.go is a simple web framework for use in Google AppEngine. Just copy the app folder to your working folder and import it fro

Mar 21, 2021
Eudore is the core of a golang lightweight web framework.

Eudore eudore是一个golang轻量级web框架核心,可以轻松扩展成一个技术栈专用框架,具有完整框架设计体系。 反馈和交流请加群组:QQ群373278915。 Features 易扩展:主要设计目标、核心全部解耦,接口即为逻辑。 简单:对象语义明确,框架代码量少复杂度低,无依赖库。 易用

Nov 7, 2022
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Gin Web Framework Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks

Jan 2, 2023
Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

Sep 27, 2021
a golang web mvc framework, like asp.net mvc.

goku goku is a Web Mvc Framework for golang, mostly like ASP.NET MVC. doc & api Installation To install goku, simply run go get github.com/QLeelulu/go

Dec 7, 2022
package for building REST-style Web Services using Go

go-restful package for building REST-style Web Services using Google Go Code examples using v3 REST asks developers to use HTTP methods explicitly and

Jan 1, 2023
A high level web-framework for Go

go-start is a high level web-framework for Go, like Django for Python or Rails for Ruby. Installation: go get github.com/ungerik/go-start Documentatio

Dec 24, 2022
A lightweight RESTful web framework for Go
A lightweight RESTful web framework for Go

Goweb A lightweight RESTful web framework for Go. For examples and usage, please read the Goweb API Documentation Read our Articles Who uses Goweb? "U

Dec 12, 2022
Fast and Reliable Golang Web Framework
Fast and Reliable Golang Web Framework

Gramework The Good Framework Gramework long-term testing stand metrics screenshot made with Gramework Stats Dashboard and metrics middleware What is i

Dec 18, 2022
Mango is a modular web-application framework for Go, inspired by Rack, and PEP333.

Mango Mango is a modular web-application framework for Go, inspired by Rack and PEP333. Note: Not actively maintained. Overview Mango is most of all a

Nov 17, 2022
Classy web framework for Go

Martini NOTE: The martini framework is no longer maintained. Martini is a powerful package for quickly writing modular web applications/services in Go

Dec 29, 2022
A Go framework for building JSON web services inspired by Dropwizard

Tiger Tonic A Go framework for building JSON web services inspired by Dropwizard. If HTML is your game, this will hurt a little. Like the Go language

Dec 9, 2022
The web framework for Golang
The web framework for Golang

uAdmin the Golang Web Framework Easy to use, blazing fast and secure. Originally open source by IntegrityNet Solutions and Services For Documentation:

Dec 24, 2022
Simple web framework for go, still quite beta at this point

WFDR Framework - Beta Release New 18/Feb/2012: Updated for go 1.0, new directory layout to take advantage of the go build tool. Background There's a m

Feb 11, 2021
The easiest way to make API documents for GraphQL

Document Generator for GraphQL gqldoc is now alpha gqldoc is command line tool to generate documents from GraphQL schema or your GraphQL endpoint. the

Dec 20, 2022
The easiest, most secure way to use WireGuard and 2FA.

This repository contains all the open source Tailscale client code and the tailscaled daemon and tailscale CLI tool. The tailscaled daemon runs primarily on Linux; it also works to varying degrees on FreeBSD, OpenBSD, Darwin, and Windows.

Jan 8, 2023