Skip to content

spl3g/chttp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

chttp

This is not really a library, but a little project for my education. But if you really want to use it, you can.

Installation

make static
# or
make shared

Copy the directory in the include/ folder to your project.

Usage

Initializing the server

arena arena = {0};
http_server serv = {0};
if (init_server(&arena, &serv, "127.0.0.1", "6969") != 0) {
  return 1;
}

Adding handlers

http_handler *hello_world_handler = http_handle_path(&serv, "GET", "/", hello_world);

void hello_world(http_request req) {
  req.resp->code = OK;
  req.resp->body = CS("Hello world!\n");
  http_send(req);
}

Adding middleware

http_register_global_middleware(&serv, logging_func);
// or
http_register_handler_middleware(&arena, hello_world_handler, logging_func);

void logging_func(http_middleware *self, http_request req) {
  // you have to run http_run_next to run the next middleware
  http_run_next(self, req);
  // or you can just send the response
  // http_send(req);
  
  http_log(HTTP_INFO, CS_FMT" "CS_FMT": %ld\n", CS_ARG(req.method), CS_ARG(req.path), req.resp->code);
}

Listening for requests

And to wrap things up, we need to run

listen_and_serve(&serv);

Full example

#include <chttp/http.h>
#include <chttp/const_strings.h>

void logging_func(http_middleware *self, http_request req) {
  http_run_next(self, req);
  http_log(HTTP_INFO, CS_FMT" "CS_FMT": %ld\n", CS_ARG(req.method), CS_ARG(req.path), req.resp->code);
}

void hello_world(http_request req) {
  req.resp->code = OK;
  req.resp->body = CS("Hello world!\n");
  http_send(req);
}

int main() {
  arena arena = {0};
  http_server serv = {0};
  if (init_server(&arena, &serv, "127.0.0.1", "6969") != 0) {
	return 1;
  }

  http_handler *hello_world_handler = http_handle_path(&serv, "GET", "/", hello_world);
  http_register_handler_middleware(&arena, hello_world_handler, logging_func);
  http_register_global_middleware(&serv, logging_func);

  listen_and_serve(&serv);

  return 0;
}

About

A really simple (and not finished) http server in c

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published