フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

WSL/ubuntuにpython/golangをインストールしてローカル環境でvercelの開発をする

はじめに

  • vercelでserverless functionが利用できるようになっていたので、ローカルで少し動かしてみる。PythonGolangRuby、Nodeも使えるらしい。 vercel.com

  • serverless functionは利用できるがメモリなどの制限があるため、何か簡単な処理か、どうしてもサーバー側で処理しないといけないものにとどめておいた方がよさそう。果たしてそんな処理があるのか・・・。 vercel.com

WSL/ ubunts環境にgolangPythonをインストール

golangのインストール

$ sudo add-apt-repository ppa:longsleep/golang-backports
$ sudo apt update
$ sudo apt install golang
$ go version

pythonをインストール

1.下記のサイトからソースファイルをダウンロードする。
https://www.python.org/downloads/source/

2.下記のようにエクスプローラーから直接ダウンロードしたファイルをwsl環境の好きな場所に配置する
[f:id:PX-WING:20211028083247p:plain]

3.下記のコマンドを実行する

tar xf Python-3.10.0.tgz
 cd Python-3.10.0/
./configure
 make
 make install
  • vercelのAPIフォルダにgoとpythonのファイルを設置する f:id:PX-WING:20211030113452p:plain

設置したファイルの中身

golang

  • vercelでプロジェクト作成したときにdefaultで作成されるファイル
package handler

import (
    "fmt"
    "net/http"
    "time"
)

func Handler(w http.ResponseWriter, r *http.Request) {
    currentTime := time.Now().Format(time.RFC850)
    fmt.Fprintf(w, currentTime)
}

python

  • api/index.pyファイルの中身は下記のように記述する
from http.server import BaseHTTPRequestHandler
from urllib import parse
class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        s = self.path
        dic = dict(parse.parse_qsl(parse.urlsplit(s).query))
        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()
        if "name" in dic:
            message = "Hello, " + dic["name"] + "!"
        else:
            message = "Hello, stranger!"
        self.wfile.write(message.encode())
        return  

React側の呼び出し

import React from 'react';
import { useEffect, useState } from 'react';
import './App.css';

function App() {
  const [date, setDate] = useState(null);
  const [message, setMessage] = useState('');
  useEffect(() => {
    async function getDate() {
      // GoのAPIの呼び出す
      const res = await fetch('/api/date');
      const newDate = await res.text();
      // PythonのAPIを呼び出す
      const res2 = await fetch('/api/index');
      const newMessage = await res2.text();
      setDate(newDate);
      setMessage(newMessage);
    }
    getDate();
  }, []);
  return (
    <main>
      <h1>Create React App + Go And Pytho API</h1>
      <br />
      <h2>The date according to Go is:</h2>
      <p>{date ? date : 'Loading date...'}</p>
      <h2>The Message according to Python is:</h2>
      <p>{message ? message : 'Loading date...'}</p>
    </main>
  );
}

export default App;

実行結果

f:id:PX-WING:20211030113756p:plain