To be an better Gopher, get your hands dirty. Topcoder offered a serials of challenges for learning Golang.

In this blog, I tried to implement "Go Learning Challenge - Simple Web-API Server"[1].

What's used in this challenge ? Following aspects and packages will be covered in this challenge

  • How to create a HTTP server: net/http
  • How to create routers (handlers for different URLs): regex + url
  • How to write HTTP responses: net/http
  • How to load JSON config: json + io/ioutil
  • How to parse URL query string: url
  • How to encode data in sha256/base64: sha256/base64  + strings
  • How to write tests in Golang: testing
  • How to parse command line arguments: flag
  • How to log: log

Configuration File example:

[
{
"domain": "topcoder.com",
"users": [
{
"username": "takumi",
"password": "ilovego"
},
{
"username": "teru",
"password": "ilovejava"
},
{
"username": "toshi",
"password": "iloveapex"
}
]
},
{
"domain": "appirio.com",
"users": [
{
"username": "jun",
"password": "ilovetopcoder"
},
{
"username": "narinder",
"password": "ilovesamurai"
},
{
"username": "chris",
"password": "ilovesushi"
}
]
}
]

config.go

package SimpleWebAPIServer

import (
"io/ioutil"
"encoding/json"
"errors"
) type User struct {
UserName string `json:"username"`
Password string `json:"password"`
} type Domain struct {
Name string `json:"domain"`
Users UserList `json:"users"`
} type DomainWarehouse []Domain
type UserList []User func ReadConfig(fn string) (DomainWarehouse, error) {
data, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
//fmt.Println(string(data)) var m DomainWarehouse
json.Unmarshal(data, &m)
return m, nil
} func (dw DomainWarehouse) GetDomain(name string) (*Domain, error) {
for _, domain := range dw {
if domain.Name == name {
return &domain, nil
}
}
return nil, errors.New("Failed to find domain")
} func (ul UserList) GetUser(username string) (*User, error) {
for _, user := range ul {
if user.UserName == username {
return &user, nil
}
}
return nil, errors.New("Failed to find user")
}

tests for config.go

package SimpleWebAPIServer

import (
"testing"
"fmt"
) func TestReadConfig(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
if dw == nil || len(dw) != {
t.Error("Failed to unmarshal json objects")
} if dw[].Name != "topcoder.com" || len(dw[].Users) != {
t.Error("Incorrect value")
}
} func TestGetDomain(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
}
} func TestGetUser(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
} ul := domain.Users
u, err := ul.GetUser("takumi")
if err != nil {
t.Error("Failed to get user")
}
if u.UserName != "takumi" || u.Password != "ilovego" {
t.Error("Invalid user values")
}
}

After implementing this simple web api server, I got better understanding of Golang syntax and Web API stuffs. For more Web API server challenges, go to [3] about OAuth2.

[1] topcoder : http://www.topcoder.com/challenge-details/30046011/?type=develop&noncache=true

[2] git : https://coding.net/u/huys03/p/SimpleWebAPIServer/git

[3] next challenge: http://www.topcoder.com/challenge-details/30046224/?type=develop

Simple Web API Server in Golang (1)的更多相关文章

  1. Simple Web API Server in Golang (2)

    In this challenge, I tried to implement a simple OAuth2 server basing on Simple Web API Server in [1 ...

  2. 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API

    原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...

  3. 【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)

    HTTP is not just for serving up web pages. It's also a powerful platform for building APIs that expo ...

  4. [转]【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)

    本文转自:https://www.cnblogs.com/inday/p/6288707.html HTTP is not just for serving up web pages. It’s al ...

  5. Running Web API using Docker and Kubernetes

    Context As companies are continuously seeking ways to become more Agile and embracing DevOps culture ...

  6. [转]Enabling CRUD Operations in ASP.NET Web API 1

    本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...

  7. Asp.Net MVC 4 Web API 中的安全认证-使用OAuth

    各种语言实现的oauth认证: http://oauth.net/code/ 上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证. 这里说明一个如何使用oa ...

  8. Creating A Simple Web Server With Golang

    原文:https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/ -------------------- ...

  9. [转]Getting started with ASP.NET Web API OData in 3 simple steps

    本文转自:https://blogs.msdn.microsoft.com/webdev/2013/01/29/getting-started-with-asp-net-web-api-odata-i ...

随机推荐

  1. js中的async await

    JavaScript 中的 async/await 是属于比较新的知识,在ES7中被提案在列,然而我们强大的babel粑粑已经对它进行列支持! 如果开发中使用了babel转码,那么就放心大胆的用吧. ...

  2. HDU 5112 A Curious Matt (2014ACM/ICPC亚洲区北京站-重现赛)

    A Curious Matt Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 512000/512000 K (Java/Others) ...

  3. redis scan迭代模糊匹配

    $redis = new Redis(); $redis->connect('localhost', 6379); $iterator = null; while (true) { $keys ...

  4. 谈谈Java引用和Threadlocal的那些事

    1 背景 某一天在某一个群里面的某个群友突然提出了一个问题:"threadlocal的key是虚引用,那么在threadlocal.get()的时候,发生GC之后,key是否是null?&q ...

  5. Mac 删除应用卸载后无法正常移除的图标

    经常会不通过appstore下载软件,也就是从网页中下载dmg,自己安装,但是当我不再想要这个软件,然后把它卸载掉之后就会发现,launchpad里还是遗留了这个软件的图标,而且删不掉.这个时候,就可 ...

  6. error while loading shared libraries: libmysqlcppconn.so.7: cannot open shared object file: No such file or directory

    1. 即使libmysqlcppconn.so.7和与之相关存在,也报这个错误. 解决方法:临时添加LD_LIBRARY_PATH, 假使 libmysqlcppconn.so在/usr/local/ ...

  7. 检测传入字符串是否存在重复字符,返回boolean

    检测传入字符串是否存在重复字符,返回boolean,比如"abc"返回true:"aac"返回false 这里提供两种思路: 第一种: import java. ...

  8. Angular的依赖注入(依赖反转)原理说明

    依赖注入(依赖反转)意思是由函数决定要引入什么样的依赖: let mod = angular.module('test',[]); mod.controller('test_c',function($ ...

  9. 在同一个表中将varchar2类型的数据转存到blob类型的字段中

    用一条修改语句即可:update t_content set f_body=rawtohex(f_check) where f_type in (0,4)此处须用rawtohex()函数将f_chec ...

  10. Windows环境下Qwt安装和使用

    之前安装过,现在记录下关键步骤,方便后面使用和复习吧. 环境:win10   Qt5.9  Qt Creator 4.3 参考:https://blog.csdn.net/linuxarmsummar ...